import { asyncTasks } from '../utils/roc'
import db from '../app/database'
import { md5 } from '../utils/crypto-utils'
import redisClient from '../app/redis'
import Api from '../utils/Api'

class RegisterService extends Api {
  /**
   * 用户注册
   */
  async register(
    nickname: string,
    username: string,
    password: string,
    uuid: string,
    captcha: string,
  ) {
    if (!uuid) {
      return this.error('uuid为空!')
    }
    const redisCaptcha = await redisClient.get(uuid)
    if (!nickname) {
      return this.error('昵称为空!')
    } else if (!username) {
      return this.error('用户名为空!')
    } else if (!password) {
      return this.error('密码为空!')
    } else if (!captcha) {
      return this.error('验证码为空!')
    } else if (captcha !== redisCaptcha) {
      return this.error('验证码错误!')
    }
    const selectSql = 'SELECT * FROM roc_user WHERE username = ?'
    const [err1, results1] = await asyncTasks(db.query(selectSql, [username]))
    if (err1) return console.log('sql错误:', err1.sqlMessage)
    const users = results1[0]
    if (users.length) return this.error('用户名已存在')
    const sqlInsert =
      'INSERT INTO roc_user(nickname, username, password, add_time) VALUES(?, ?, ?, ?)'
    const [err, results] = await asyncTasks(
      db.query(sqlInsert, [nickname, username, md5(password), new Date()]),
    )
    if (err) return console.log('sql错误:', err.sqlMessage)
    await redisClient.del(uuid)
    return this.success(results[0].insertId)
  }
}

export default new RegisterService()
